# -*- coding: utf-8 -*-
from typing import Sequence

from sqlalchemy import Select

from {{ crud_import_path }} import {{ table_name_class }}Dao
from {{ model_import_path }} import {{ table_name_class }}
from {{ schema_import_path }} import Create{{ schema_name }}Param, Update{{ schema_name }}Param
from App.common.exception import errors
from App.database.mysql import async_db_session


class {{ table_name_class }}Services:
    @staticmethod
    async def get(*, pk: int) -> {{ table_name_class }}:
        async with async_db_session() as db:
            {{ table_name_en }} = await {{ table_name_class }}Dao.get(db, pk)
            if not {{ table_name_en }}:
                raise errors.NotFoundError(message='{{ table_simple_name_zh }}不存在')
            return {{ table_name_en }}

    @staticmethod
    async def get_select() -> Select:
        return await {{ table_name_class }}Dao.get_list()

    @staticmethod
    async def get_all() -> Sequence[{{ table_name_class }}]:
        async with async_db_session() as db:
            {{ table_name_en }}s = await {{ table_name_class }}Dao.get_all(db)
            return {{ table_name_en }}s

    @staticmethod
    async def create(*, obj_in: Create{{ schema_name }}Param) -> {{ table_name_class }}:
        async with async_db_session.begin() as db:
            return await {{ table_name_class }}Dao.create(db, obj_in)

    @staticmethod
    async def update(*, obj_in: Update{{ schema_name }}Param) -> int:
        async with async_db_session.begin() as db:
            pk = obj_in.id
            count = await {{ table_name_class }}Dao.update(db, pk, obj_in)
            return count

    @staticmethod
    async def delete(*, pk: int) -> int:
        async with async_db_session.begin() as db:
            count = await {{ table_name_class }}Dao.delete(db, pk)
            return count


{{ table_name_class }}Service: {{ table_name_class }}Services = {{ table_name_class }}Services()
